package com.xizimall.portal.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.xizimall.pojo.TbUser;
import com.xizimall.portal.service.UserService;
import com.xizimall.portal.service.impl.UserServiceImpl;
import com.xizimall.common.utils.CookieUtils;

public class LoginInterceptor implements HandlerInterceptor {
    
	@Autowired
	private UserServiceImpl userService;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		//在Handler执行之前处理,返回值绝对是否执行,true执行,false不执行
		//判断是否登录
		//从cookie中取token
		String token = CookieUtils.getCookieValue(request, "TT_TOKEN");
		//根据token取用户信息,调用SSO系统的服务
		TbUser user= userService.getUserByToken(token);
		//取不到用户信息,跳转到登录页面,把用户请求的url传递给登录页面
		if(null==user){
			response.sendRedirect(userService.SSO_BASE_URL+userService.SSO_PAGE_LOGIN+"?redirect="+request.getRequestURL());
			//返回false
			return false;
		}
		//把用户信息放入request
		request.setAttribute("user", user);
		//取到用户信息,返回true
		return true;
		
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		//返回ModelAndView之后,响应用户之后

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// TODO Auto-generated method stub

	}

}
